package ua.kharkov.knure.pereverziev.diploma.db.DAOServices;

import java.math.BigInteger;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ua.kharkov.knure.pereverziev.diploma.db.entity.Flight;
import ua.kharkov.knure.pereverziev.diploma.db.entity.Ticket;
import ua.kharkov.knure.pereverziev.diploma.db.entity.User;

public class TicketService extends CommonService<Ticket> {

	private final Logger log = LoggerFactory.getLogger(TicketService.class);

	public TicketService() {
		super(Ticket.class);
	}

	public long getEmptySitsQuantity(final long flightNumber) {
		log.debug("getEmptySitsQuantity --- > " + flightNumber);
		final Criteria criteria = HibernateUtils.getSession().createCriteria(
				Ticket.class);
		criteria.add(Restrictions.eq("flights", new Flight(flightNumber)));
		criteria.setProjection(Projections.rowCount());
		return (Long) criteria.list().get(0);
	}

	@SuppressWarnings("unchecked")
	public List<Ticket> getUserTickets(final User user) {
		final Criteria criteria = HibernateUtils.getSession().createCriteria(
				Ticket.class);
		criteria.add(Restrictions.eq("user", user));
		return criteria.list();
	}

	public Set<Ticket> getUserTicketsSet(final User user) {
		final TreeSet<Ticket> result = new TreeSet<Ticket>();
		final Criteria criteria = HibernateUtils.getSession().createCriteria(
				Ticket.class);
		criteria.add(Restrictions.eq("user", user));
		result.addAll(criteria.list());
		return result;
	}

	public int getEmptySitsQuantity(final Flight flight) {
		final String sqlQuery = "SELECT COUNT(*) FROM ticket_flights WHERE flights_flight_id="
				+ flight.getId();
		final Query query = HibernateUtils.getSession()
				.createSQLQuery(sqlQuery);
		// query.setParameter(1, flight.getId());
		return ((BigInteger) query.uniqueResult()).intValue();
	}
}
